﻿#include "smartserver.h"
#include "ui_smartserver.h"
#include<QByteArray>
#include<QDataStream>
#include<QTcpSocket>
#include<QMessageBox>
#pragma execution_character_set("utf-8")
SmartServer::SmartServer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SmartServer)
{
    ui->setupUi(this);
    version="v1.3";//初始化
    ui->lineEdit_version->setText(version);
    tcpserver=new QTcpServer(this);
    if(!tcpserver->listen(QHostAddress::Any,6666))//开始监听任何连在6666端口的IP地址
    {
        qDebug()<<tcpserver->errorString();
        close();
    }
     connect(tcpserver,&QTcpServer::newConnection,this,&SmartServer::sendmassage);//当有客户端连接过来时，发射sendMessage
}

SmartServer::~SmartServer()
{
    delete ui;
}

void SmartServer::on_pushButton_setVersion_clicked()
{

    version=ui->lineEdit_version->text();
    QMessageBox::about(NULL,"提示","设置成功");

}
void SmartServer::sendmassage()
{

    QByteArray Array;
    QDataStream stream(&Array,QIODevice::WriteOnly);
    stream.setVersion(QDataStream::Qt_5_5);
    stream<<(quint16)0;
    stream<<version;//传入版本号
    stream.device()->seek(0);
    stream<<(quint16)(Array.size()-sizeof(quint16));
    QTcpSocket *connection=tcpserver->nextPendingConnection();//获取已连接的套接字
    connect(connection,&QTcpSocket::disconnected,connection,&QTcpSocket::deleteLater);//断开连接时删除套接字
    connection->write(Array);
    connection->disconnectFromHost();//一直等待发送完成
    //QMessageBox::about(NULL,"提示","发送成功");
    //qDebug()<<version;
    ui->label_status->setText("发送成功");
}
